#!/bin/bash

# 包含 definitions.sh
source ./definitions.sh
# 包含 functions.sh
source ./functions.sh

# 判断是否有 root 权限
if [[ $EUID -eq 0 ]]; then
    : # echo "${green}当前 Shell 已经是 root 权限${reset}"
else
    echo "${red}当前 Shell 没有 root权限，请以 root 权限运行${reset}"
    exit 1
fi

echo "启动容器"
docker-compose up -d

# ====================================================================================================
# 配置 onlyoffice 容器
containerName="onlyoffice"
echo "⏳ 等待容器 $containerName 变为 running 状态..."
# 等待容器运行
waitForContainerRunning $containerName $waitTimeout $sleepTime
if [[ $? -eq 1 ]]; then
    echo "${yellow}等待超时：容器 $containerName 在超时时间 ${waitTimeout}s 后仍未进入 running 状态${reset}"
    exit 1
fi
echo "容器 ${green}$containerName${reset} 已成功进入 ${green}running${reset} 状态"
echo "开始配置 容器 $containerName$ ..."

docker-compose exec ${containerName} cat /etc/onlyoffice/documentserver/default.json | \
jq '(.services.CoAuthoring.requestDefaults.rejectUnauthorized) = false' > onlyoffice.json && \
docker-compose cp onlyoffice.json ${containerName}:/etc/onlyoffice/documentserver/default.json >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
    rm -f onlyoffice.json
    echo "${red}配置容器 $containerName 失败：向容器中复制配置文件失败 ${reset}"
    exit 1
fi
rm -f onlyoffice.json
echo "${green}配置容器 $containerName 完成${reset}"
# ====================================================================================================
# 配置 nextcloud 容器
containerName="nextcloud"
echo "⏳ 等待容器 $containerName 变为 running 状态..."
# 等待容器运行
waitForContainerRunning $containerName $waitTimeout $sleepTime
if [[ $? -eq 1 ]]; then
    echo "${yellow}等待超时：容器 $containerName 在超时时间 ${waitTimeout}s 后仍未进入 running 状态${reset}"
    exit 1
fi
echo "容器 ${green}$containerName${reset} 已成功进入 ${green}running${reset} 状态"
echo "开始配置 容器 $containerName ..."

docker-compose exec $containerName php occ maintenance:repair --include-expensive >/dev/null 2>&1
docker-compose exec $containerName php occ config:system:set maintenance_window_start --type=integer --value=1 >/dev/null 2>&1

echo "${green}配置容器 $containerName 完成${reset}"
# ====================================================================================================
echo "正在重启容器 $containerName"
docker-compose restart
echo "容器 $containerName 重启完成"

